package org.abc.fund.service.dataSourceCollection;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.abc.fund.service.tools.StreamGobbler;
import org.springframework.beans.factory.annotation.Value;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.abc.fund.dto.dataSource.JoinQuantResultDTO;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
@Slf4j
public class JoinQuantDataIngestionService {
    private final ObjectMapper objectMapper;
    /**
     * Python解释器路径，从配置文件中读取
     * 如果未配置，默认使用 "python3"
     */
    @Value("${data.collection.python.interpreter.path:python3}")
    private String pythonInterpreterPath;

    public JoinQuantResultDTO ingestData(String username, String password, Map<String, Object> params) {
        try {
            String dataType = (String) params.getOrDefault("data_type", "unknown");
            String scriptName = getScriptNameForDataType(dataType);
            
            String scriptPath = getClass().getClassLoader().getResource("scripts/" + scriptName).getPath();
            if (System.getProperty("os.name").toLowerCase().startsWith("windows")) {
                scriptPath = scriptPath.substring(1); // Remove leading '/' on Windows
            }
            log.info("使用脚本 {} 处理数据类型 {}", scriptName, dataType);
            Map<String, Object> scriptArgs = Map.of(
                    "username", username,
                    "password", password,
                    "params", params
            );
            String scriptArgsJson = objectMapper.writeValueAsString(scriptArgs);
            ProcessBuilder processBuilder = new ProcessBuilder(pythonInterpreterPath, scriptPath);
            processBuilder.environment().put("PYTHONIOENCODING", "UTF-8");
            processBuilder.environment().put("PYTHONUTF8", "1");

            log.info("开始执行 JoinQuant 数据采集脚本，数据类型：{}", params.get("data_type"));
            log.debug("脚本入参JSON：{}", scriptArgsJson);

            Process process = processBuilder.start();

            try (var writer = new java.io.OutputStreamWriter(process.getOutputStream(), StandardCharsets.UTF_8)) {
                writer.write(scriptArgsJson);
                writer.flush();
            }

            StreamGobbler outputGobbler = new StreamGobbler(process.getInputStream());
            StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream());
            new Thread(outputGobbler).start();
            new Thread(errorGobbler).start();

            boolean finished = process.waitFor(5, TimeUnit.MINUTES);
            if (!finished) {
                process.destroyForcibly();
                throw new RuntimeException("JoinQuant 脚本执行超时");
            }

            int exitCode = process.exitValue();
            String output = outputGobbler.getOutput();
            String errorOutput = errorGobbler.getOutput();
            if (exitCode != 0) {
                throw new RuntimeException("JoinQuant 脚本执行失败，退出码 " + exitCode + "，错误信息：" + errorOutput);
            }

            if (output.isEmpty()) {
                throw new RuntimeException("JoinQuant 脚本未返回任何输出");
            }

            log.debug("Python脚本raw输出: {}", output);

            String jsonOutput = output;
            int jsonStartIndex = output.indexOf('{');
            if (jsonStartIndex == -1) {
                throw new RuntimeException("Python 脚本输出不是合法的 JSON 数据");
            }
            if (jsonStartIndex > 0) {
                jsonOutput = output.substring(jsonStartIndex);
            }
            JoinQuantResultDTO resultDTO =
                    objectMapper.readValue(jsonOutput, JoinQuantResultDTO.class);
            return resultDTO;
        } catch (Exception e) {
            throw new RuntimeException("采集失败", e);
        }
    }

    private String getScriptNameForDataType(String dataType) {
                return "dataCollectionPy.py";
        }

}

